# all the imports
import sqlite3
from flask import Flask, request, session, g, redirect, url_for
from flask import abort, render_template, flash
from tsql import *
# configuration
DEBUG = True
SECRET_KEY = 'development key'

# create out little application
app = Flask(__name__)
app.config.from_object(__name__)


# get the database session

@app.route('/')
def show_entries():
    cur = g.db.execute('select userid, title, text ,id from entries order by id desc')
    entries = [dict(userid=row[0], title=row[1], text=row[2], id=row[3]) for row in cur.fetchall()]
    # print entries[0]['id']
    return render_template('show_entries.html', entries=entries)


@app.route('/view_blog', methods=['GET', 'POST'])
def view_blog():
    id = request.args.get('entry_id')
    cur = g.db.execute('select userid, title, text, id from entries where id=?', (id,))
    view = cur.fetchone()

    if request.method == 'POST':
        g.db.execute('insert into comment (entries_id, comment_author_id, comment_text) values(?,?,?)',
                     [view[3], session['cur_user_id'], request.form['text']])
        g.db.commit()

    com = g.db.execute('select comment_author_id, comment_text from comment where entries_id=?', (view[3],))
    com_list = com.fetchall()
    return render_template('view_blog.html', view=view, com_list=com_list, id=id)


def manage_show():
    userid = session['cur_user_id']
    cur = g.db.execute('select id, title, text, userid from entries where userid=?', (userid,))
    all_blog = [dict(id=row[0], title=row[1], text=row[2], userid=row[3]) for row in cur.fetchall()]
    return all_blog


@app.route('/manage_del', methods=['GET', 'POST'])
def manage_del():
    id = request.args.get('id')
    g.db.execute('delete from entries where id=?', (id,))
    g.db.execute('delete from comment where entries_id=?', (id,))
    g.db.commit()
    manage()
    return redirect(url_for('manage'))


def modify_show(id):
    cur = g.db.execute('select id, title, text, userid from entries where id=?', (id,))
    cur_blog = [dict(id=row[0], title=row[1], text=row[2], userid=row[3]) for row in cur.fetchall()]
    return cur_blog


@app.route('/manage_modify', methods=['GET', 'POST'])
def manage_modify():
    id = request.args.get('id')
    cur_blog = modify_show(id)
    if request.method == 'POST':
        id=request.form['blog_id']
        g.db.execute('update entries set title=?, text=? where id=?',
                     (request.form['title'], request.form['text'], id))
        g.db.commit()
        return redirect(url_for('manage'))
    cur_blog = modify_show(id)
    return render_template('modify.html', cur_blog=cur_blog, id=id)


@app.route('/manage', methods=['GET', 'POST'])
def manage():
    all_blog = manage_show()

    return render_template('manage.html', all_blog=all_blog)


def show_user():
    cur = g.db.execute('select id, name, passwd from usertable')
    users = [dict(id=row[0], name=row[1], passwd=row[2]) for row in cur.fetchall()]
    print users
    for user in users:
        print user['name'], '==', user['passwd']


@app.route('/add', methods=['POST'])
def add_entry():
    if not session.get('logged_in'):
        abort(401)
    print session['cur_username']
    print session['cur_user_id']
    g.db.execute('insert into entries (title, text, userid) values(?,?,?)',
                 [request.form['title'], request.form['text'], session['cur_user_id']])
    g.db.commit()
    flash('new entry was successfully posted')

    return redirect(url_for('show_entries'))


@app.route('/register', methods=['GET', 'POST'])
def register():
    error = None
    if request.method == 'POST':
        username = request.form['username']
        userpasswd = request.form['password']
        g.db.execute('insert into usertable (name, passwd) values(?,?)',
                     [username, userpasswd])
        g.db.commit()
        flash('you were register')
        return redirect(url_for('show_entries'))
    return render_template('register.html', error=error)


@app.route('/login', methods=['GET', 'POST'])
def login():
    show_user()
    error = None
    if request.method == 'POST':
        cur = g.db.execute('select id, name, passwd from usertable')
        users = [dict(id=row[0], name=row[1], passwd=row[2]) for row in cur.fetchall()]
        for user in users:
            if request.form['username'] != user['name']:
                error = 'Invalid username'
            elif request.form['password'] != user['passwd']:
                error = 'Invalid password'
            else:
                session['logged_in'] = True
                session['cur_username'] = request.form['username']
                session['cur_user_id'] = user['id']
                flash('you were logged in')
                print 'user id'
                return redirect(url_for('show_entries'))
    return render_template('login.html', error=error)


@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    flash('you were logged out')
    return redirect(url_for('show_entries'))


if __name__ == '__main__':
    app.run()
